﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Mail;
using System.Text;

namespace JinianNet.Net
{
    public class MailService
    {
        private SmtpClient client;

        public SmtpClient Client
        {
            get { return client; }
            set { client = value; }
        }

        public MailService()
            : this(null, 25, false)
        {
        }

        public MailService(string host, int port)
            : this(host, port, false)
        {
        }

        public MailService(string host, int port, bool enableSsl)
        {
            client = new SmtpClient();
            client.DeliveryMethod = SmtpDeliveryMethod.Network;
            if (!string.IsNullOrEmpty(host))
            {
                client.Host = host;
            }
            client.Port = port;
            client.EnableSsl = enableSsl;

        }

        private string _user;
        public string User
        {
            get { return _user; }
            set { _user = value; }
        }
        private string _password;
        public string Password
        {
            get { return _password; }
            set { _password = value; }
        }
        private string _sendmail;
        public string SendMail
        {
            get { return _sendmail; }
            set { _sendmail = value; }
        }
        private string _errormessage;
        public string ErrorMessage
        {
            get { return _errormessage; }
            private set { _errormessage = value; }
        }

        public bool Send(MailMessage message)
        {
            try
            {
                NetworkCredential credential = new NetworkCredential(User, Password);
                client.Credentials = credential;
                client.Send(message);
                return true;
            }
            catch (Exception e)
            {
                ErrorMessage = e.Message;
                return false;
            }
        }

        public bool Send(string mail, string title, string body)
        {

            MailAddress addrFrom = new MailAddress(SendMail, User, Encoding.UTF8);
            MailAddress addrTo = new MailAddress(mail, mail, Encoding.UTF8);

            using (MailMessage message = new MailMessage(addrFrom, addrTo))
            {

                message.Subject = title;
                message.SubjectEncoding = Encoding.UTF8;

                message.Body = body;
                message.BodyEncoding = Encoding.UTF8;

                message.IsBodyHtml = true;
                message.Priority = MailPriority.Normal;

                return Send(message);

            }
        }
    }
}
